package com.example.database.slice;

import com.example.database.ResourceTable;
import com.example.database.Utils;
import com.example.database.orm.TestDatabase;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.data.DatabaseHelper;
import ohos.data.distributed.common.*;
import ohos.data.distributed.user.SingleKvStore;
import ohos.data.orm.OrmContext;
import ohos.utils.zson.ZSONObject;

import java.util.ArrayList;
import java.util.List;

public class DistributedAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private Button mBtnDistributedPutKv;
    private Button mBtnDistributedGetKv;
    private Button mBtnDistributedDeleteKv;
    private Button mBtnDistributedPut;
    private Button mBtnDistributedQuery;
    private Button mBtnDistributedUpdate;
    private Button mBtnDistributedDelete;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_distributed);
        mBtnDistributedPutKv = (Button) findComponentById(ResourceTable.Id_btn_distributed_put_kv);
        mBtnDistributedPutKv.setClickedListener(this);
        mBtnDistributedGetKv = (Button) findComponentById(ResourceTable.Id_btn_distributed_get_kv);
        mBtnDistributedGetKv.setClickedListener(this);
        mBtnDistributedDeleteKv = (Button) findComponentById(ResourceTable.Id_btn_distributed_delete_kv);
        mBtnDistributedDeleteKv.setClickedListener(this);
        mBtnDistributedPut = (Button) findComponentById(ResourceTable.Id_btn_distributed_put);
        mBtnDistributedPut.setClickedListener(this);
        mBtnDistributedQuery = (Button) findComponentById(ResourceTable.Id_btn_distributed_query);
        mBtnDistributedQuery.setClickedListener(this);
        mBtnDistributedUpdate = (Button) findComponentById(ResourceTable.Id_btn_distributed_update);
        mBtnDistributedUpdate.setClickedListener(this);
        mBtnDistributedDelete = (Button) findComponentById(ResourceTable.Id_btn_distributed_delete);
        mBtnDistributedDelete.setClickedListener(this);
    }

    @Override
    public void onClick(Component component) {

        if (component.getId() == ResourceTable.Id_btn_distributed_put_kv) {

            // 获取KvStore对象
            SingleKvStore kvStore = getMySingleKvStore();
            // 通过PUT方法写入浮点型键值对
            kvStore.putFloat("floatValue", 0.6f);

            // 通过putBatch方法批量批量写入键值对
            List<Entry> entries = new ArrayList<>();
            Entry entry = new Entry("intValue", Value.get(2));
            entries.add(entry);
            Entry entry2 = new Entry("stringValue", Value.get("测试"));
            entries.add(entry2);
            kvStore.putBatch(entries);

        }
        if (component.getId() == ResourceTable.Id_btn_distributed_get_kv) {

            // 获取KvStore对象
            SingleKvStore kvStore = getMySingleKvStore();
            try {
                float floatValue = kvStore.getFloat("floatValue");
                Utils.log("floatValue: " + floatValue);
                int intValue = kvStore.getInt("intValue");
                Utils.log("intValue: " + intValue);
                String stringValue = kvStore.getString("stringValue");
                Utils.log("stringValue: " + stringValue);
            }catch (KvStoreException e) {
                Utils.log(e.toString());
            }
        }

        if (component.getId() == ResourceTable.Id_btn_distributed_delete_kv) {

            // 获取KvStore对象
            SingleKvStore kvStore = getMySingleKvStore();
            // 删除键值对
            kvStore.delete("floatValue");

        }
        if (component.getId() == ResourceTable.Id_btn_distributed_put) {

            // 获取KvStore对象
            SingleKvStore kvStore = getStudentKvStore();

            // 构建JSON对象
            ZSONObject obj = new ZSONObject();
            obj.put("name", "董昱");
            obj.put("age", 30);
            obj.put("sex", 1);
            obj.put("class", "鸿蒙基础学习班");
            // 键字符串，由前缀student_和ID 20210001组成
            String key = "student_20210001";
            // 添加结构化学生信息实体
            kvStore.putString(key, obj.toString());
        }


        if (component.getId() == ResourceTable.Id_btn_distributed_query) {

            // 获取KvStore对象
            SingleKvStore kvStore = getStudentKvStore();
            Query query = Query.select()
                    .equalTo("$.class", "鸿蒙基础学习班");
            List<Entry> entries = kvStore.getEntries(query);
            for (Entry entry : entries) {
                String key = entry.getKey();
                ZSONObject obj = ZSONObject.stringToZSON(entry.getValue().getString());
                String name = obj.getString("name");
                int age = obj.getInteger("age");
                int sex = obj.getInteger("sex");
                String _class = obj.getString("class");
                Utils.log("key:" + key
                        + " name:" + name
                        + " age:" + age
                        + " sex:" + sex
                        + " class:" + _class);
            }
        }

        if (component.getId() == ResourceTable.Id_btn_distributed_update) {

            // 获取KvStore对象
            SingleKvStore kvStore = getStudentKvStore();
            try {
                // 获得董昱学生信息的ZSON对象
                String jsonStr = kvStore.getString("student_20210001");
                ZSONObject obj = ZSONObject.stringToZSON(jsonStr);
                // 修改信息后转换为JSON字符串
                obj.put("class", "鸿蒙高级学习班");
                // 更新数据
                kvStore.putString("student_20210001", obj.toString());
            }catch (KvStoreException e) {
                Utils.log(e.toString());
            }


        }

        if (component.getId() == ResourceTable.Id_btn_distributed_delete) {

            // 获取KvStore对象
            SingleKvStore kvStore = getStudentKvStore();
            kvStore.delete("student_20210001");
        }
    }


    /**
     * 获取测试数据库myStore的SingleKvStore对象
     *
     * @return SingleKvStore对象
     */
    private SingleKvStore getMySingleKvStore() {
        // 创建KvManagerConfig对象
        KvManagerConfig config = new KvManagerConfig(this);
        // 通过KvManagerFactory单例创建KvManager对象
        KvManager kvManager = KvManagerFactory.getInstance().createKvManager(config);
        // 创建数据库配置对象options
        Options options = new Options().setCreateIfMissing(true)
                .setEncrypt(false)
                .setAutoSync(true)
                .setBackup(true)
                .setKvStoreType(KvStoreType.SINGLE_VERSION);
        // 创建数据库并获得SingleKvStore对象
        SingleKvStore kvStore = kvManager.getKvStore(options, "myStore");
        return kvStore;
    }

    /**
     * 获取测试数据库students的SingleKvStore对象
     *
     * @return SingleKvStore对象
     */
    private SingleKvStore getStudentKvStore() {
        // 创建KvManagerConfig对象
        KvManagerConfig config = new KvManagerConfig(this);
        // 通过KvManagerFactory单例创建KvManager对象
        KvManager kvManager = KvManagerFactory.getInstance().createKvManager(config);
        // 创建数据库配置对象options
        Options options = new Options().setCreateIfMissing(true)
                .setEncrypt(false)
                .setAutoSync(true)
                .setBackup(true)
                .setKvStoreType(KvStoreType.SINGLE_VERSION)
                .setSchema(generateStudentSchema());
        // 创建数据库并获得SingleKvStore对象
        SingleKvStore kvStore = kvManager.getKvStore(options, "students");
        return kvStore;
    }

    /**
     * 生成学生信息Schema
     * @return
     */
    private Schema generateStudentSchema() {
        Schema schema = new Schema();
        // 兼容模式
        schema.setSchemaMode(SchemaMode.COMPATIBLE);

        // 姓名属性
        FieldNode nameNode = new FieldNode("name");
        nameNode.setType(FieldValueType.STRING); // 字符串类型
        schema.getRootFieldNode().appendChild(nameNode);

        // 年龄属性
        FieldNode ageNode = new FieldNode("age");
        ageNode.setType(FieldValueType.INTEGER); // 整型
        schema.getRootFieldNode().appendChild(ageNode);

        // 性别属性
        FieldNode sexNode = new FieldNode("sex");
        sexNode.setType(FieldValueType.INTEGER); // 整型
        schema.getRootFieldNode().appendChild(sexNode);

        // 班级属性
        FieldNode classNode = new FieldNode("class");
        classNode.setType(FieldValueType.STRING); // 字符串类型
        schema.getRootFieldNode().appendChild(classNode);

        return schema;
    }
}
